package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechError;
import com.iflytek.speech.SpeechConfig.RATE;
import com.iflytek.ui.RecognizerDialog;
import com.iflytek.ui.RecognizerDialogListener;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.PushMessage;
import com.myapp.ruyixing.ui.widget.DocIndicator;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
public class SearchFragment extends Fragment implements OnClickListener,
		OnEditorActionListener, OnPageChangeListener, RecognizerDialogListener {

	private static ArrayList<View> mList = new ArrayList<View>();;
	private DocIndicator mDocIndicator;
	private ViewPager mViewPager;
	private static boolean sPushMessageLoaded = false;
	private static boolean sShowPushMessage = false;

	private RecognizerDialog iatDialog;
	private EditText mSearchEditText;

	class TapGestureListener extends GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			int i = mViewPager.getCurrentItem();
			View view = mList.get(i);
			String url = (String) view.getTag();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse(url));
			startActivity(intent);
			return true;
		}
	}

	private GestureDetector tapGestureDetector = new GestureDetector(
			getActivity(), new TapGestureListener());

	private PagerAdapter mAdapter = new MyAdapter();

	private class MyAdapter extends PagerAdapter {

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = mList.get(position);
			((ViewPager) container).addView(view, 0);
			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(mList.get(position));// 删除页卡
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;// 官方提示这样写
		}

		@Override
		public int getCount() {

			return mList.size();
		}
	};

	public SearchFragment() {
		// Required empty public constructor
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.fragment_search, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		mDocIndicator = (DocIndicator) view.findViewById(R.id.indicator);
		mDocIndicator.setTotal(mList.size());
		mDocIndicator.setCurrent(0);

		mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOnPageChangeListener(this);

		mViewPager.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				tapGestureDetector.onTouchEvent(event);
				return false;
			}
		});

		view.findViewById(R.id.btn_close).setOnClickListener(this);
		view.findViewById(R.id.search_city).setOnClickListener(this);
		view.findViewById(R.id.layout_food).setOnClickListener(this);
		view.findViewById(R.id.text_city).setOnClickListener(this);

		view.findViewById(R.id.nearby_more).setOnClickListener(this);
		view.findViewById(R.id.nearby_entertainment).setOnClickListener(this);
		view.findViewById(R.id.nearby_food).setOnClickListener(this);
		view.findViewById(R.id.nearby_hotel).setOnClickListener(this);
		view.findViewById(R.id.nearby_travel).setOnClickListener(this);
		view.findViewById(R.id.nearby_walk).setOnClickListener(this);
		view.findViewById(R.id.img_voice).setOnClickListener(this);
		view.findViewById(R.id.nearby_scoreshop).setOnClickListener(this);

		view.findViewById(R.id.search_top).setOnClickListener(this);
		view.findViewById(R.id.layout_discount).setOnClickListener(this);
		view.findViewById(R.id.img_voice).setOnClickListener(this);

		mSearchEditText = (EditText) view.findViewById(R.id.edit_search);
		mSearchEditText.setOnEditorActionListener(this);
	}

	@Override
	public void onResume() {
		setCityName(Config.sCityName);
		if (CityListActivity.isCitySet(getActivity())
				&& (CityListActivity.checkCityModified() || !sPushMessageLoaded)) {
			sShowPushMessage = false;
			mViewPager.setAdapter(null);
			mAdapter = null;
			loadPushMessage();
		}
		checkLayoutADVisibility();
		super.onResume();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// init recognizer dialog
		iatDialog = new RecognizerDialog(activity, "appid="
				+ Config.VOICE_RECOGNAZE_APP_ID);
		iatDialog.setListener(this);
	}

	private void checkLayoutADVisibility() {
		if (getView() == null) {
			return;
		}
		getView().findViewById(R.id.layout_ad).setVisibility(
				sShowPushMessage ? View.VISIBLE : View.GONE);
	}

	public void loadPushMessage() {
		RYHttpClient.getPushMessage(getActivity(), new RYHttpResponseHandler() {

			@Override
			public void onSuccess(Object o) {
				try {
					showPushMessage((PushMessage) o);
					sPushMessageLoaded = true;
				} catch (Exception e) {
				}
			}

			@Override
			public void onFailure(Throwable throwable) {
			}
		}, Config.sCityId);
	}

	public void showPushMessage(PushMessage message) {
		mList.clear();
		if (message != null && message.data != null && message.data.size() > 0) {
			for (int i = 0; i < message.data.size(); i++) {
				TextView textview = (TextView) LayoutInflater.from(
						getActivity()).inflate(R.layout.text_ad, null);
				textview.setText(message.data.get(i).title);
				textview.setTag(message.data.get(i).url);
				mList.add(textview);
			}
			mAdapter = new MyAdapter();
			mViewPager.setAdapter(mAdapter);
			mDocIndicator.setTotal(mList.size());
			mDocIndicator.setCurrent(0);
			sShowPushMessage = true;
			checkLayoutADVisibility();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.text_city:
			startActivity(new Intent(getActivity(), CityListActivity.class));
			break;
		case R.id.layout_food:
			startActivity(new Intent(getActivity(), FoodListActivity.class));
			break;
		case R.id.search_city:
			startActivity(new Intent(getActivity(), SearchCityActivity.class));
			break;
		case R.id.nearby_more:
			startActivity(new Intent(getActivity(),
					SearchCityMenuActivity.class));
			break;
		case R.id.nearby_entertainment:
			startActivity(new Intent(getActivity(), NearbyStoreActivity.class)
					.putExtra(NearbyStoreActivity.INTENT_KEY_TYPE,
							"entertainment"));
			break;
		case R.id.nearby_food:
			startActivity(new Intent(getActivity(), NearbyStoreActivity.class)
					.putExtra(NearbyStoreActivity.INTENT_KEY_TYPE, "food"));
			break;
		case R.id.nearby_hotel:
			startActivity(new Intent(getActivity(), NearbyStoreActivity.class)
					.putExtra(NearbyStoreActivity.INTENT_KEY_TYPE, "hotel"));
			break;
		case R.id.nearby_travel:
			startActivity(new Intent(getActivity(), NearbyStoreActivity.class)
					.putExtra(NearbyStoreActivity.INTENT_KEY_TYPE, "travel"));
			break;
		case R.id.nearby_walk:
			startActivity(new Intent(getActivity(),
					AirAndTrainSearchActivity.class));
			break;
		case R.id.search_top:
			startActivity(new Intent(getActivity(), RankActivity.class));
			break;
		case R.id.layout_discount:
			startActivity(new Intent(getActivity(), DiscountActivity.class));
			break;
		case R.id.nearby_scoreshop:
			startActivity(new Intent(getActivity(), ScoreMallActivity.class));
			break;

		case R.id.btn_close:
			sShowPushMessage = false;
			checkLayoutADVisibility();
			break;

		case R.id.img_voice:
			iatDialog.setEngine("sms", "asr_ptt=0", null);
			iatDialog.setSampleRate(RATE.rate16k);
			iatDialog.show();

			break;

		default:
			break;
		}
	}

	public void setCityName(String city) {
		if (TextUtils.isEmpty(city)) {
			return;
		}
		int index = city.lastIndexOf("市");
		if (index > 0)
			city = city.substring(0, index);
		((TextView) (getView().findViewById(R.id.text_city))).setText(city);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEARCH:
			String s = mSearchEditText.getText().toString();
			s = s.trim();
			if (!TextUtils.isEmpty(s)) {
				SearchShopListActivity.startShopListActivity(getActivity(), s);
			}
			break;
		}
		return false;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		if (mDocIndicator != null) {
			mDocIndicator.setCurrent(arg0);
		}
	}

	/**
	 * RecognizerDialogListener的"结束会话"回调接口. 获取会话识别状态，若error不为空，则会话出现错误.
	 * 
	 * @param error
	 */
	@Override
	public void onEnd(SpeechError error) {
	}

	/**
	 * RecognizerDialogListener的"返回识别结果"回调接口.
	 * 可以通过对RecognizerResult进行解析获取识别结果的详细内容.
	 * 
	 * @param results
	 *            ,isLast
	 */
	@Override
	public void onResults(ArrayList<RecognizerResult> results, boolean isLast) {
		StringBuilder builder = new StringBuilder();
		for (RecognizerResult recognizerResult : results) {
			builder.append(recognizerResult.text);
		}
		if (builder.length() > 0) {
//			mSearchEditText.append(builder);
//			mSearchEditText.setSelection(mSearchEditText.length());
			SearchShopListActivity.startShopListActivity(getActivity(), builder.toString());
		}
	}
}
